import React from "react";
import {Modal, Button, Table, Checkbox, Icon} from "tinper-bee";
import FormControl from "bee-form-control";
import 'bee-form-control/build/FormControl.css';
import "./index.less";
import {targetRefQuery} from "./workgantt.config";
import multiSelect from "bee-table/build/lib/multiSelect";

const MultiSelectTable = multiSelect(Table, Checkbox);
const columns = [
    { title: "序号", dataIndex: "index", key: "index", width: 150 , render :(text, record, index)=>{
        return index + 1;
    }},

    { title: "指标编码", dataIndex: "code", key: "code", width: '20%', render :(text, record, index)=>{
        return(
            <div>
                { text }
            </div>
        )
    }},

    { title: "指标名称", dataIndex: "name", key: "name", width:'20%', render :(text, record, index)=>{
        return(
            <div>
                { text }
            </div>
        )
    }},
    { title: "计量单位", dataIndex: "unit", key: "unit", width: '20%', render :(text, record, index)=>{
        return(
            <div>
                { text }
            </div>
        )
    }},

    { title: "备注", dataIndex: "memo", key: "memo", width: '20%', render :(text, record, index)=>{
        return(
            <div>
                { text }
            </div>
        ) 
    }}
];
const tableData = [];

export default (params) => (WrappedComponent) => class ChooseTargetModal extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            showChooseModal: false,
            columns : [...columns],
            tableData:[...tableData],
            searchValue:'',
            selectedValue :[],//已经明确是哪几个的结果
            from :'',
            hasSelectedValue :[],//动态的选择的结果
            pkMap : [],
        };
    }
    
    componentDidMount (){
       this.init();
    }
    init = ()=>{
        targetRefQuery({ 'isAjax': 1, 'ieStamp': new Date().getTime()}).then((res)=>{
            if (res.data.resultCode !== 'busi_ex') {
                this.mapTableData(res.data.result)
            }
        })
    }
    filterTableData = (value) =>{
        let data =[];
        let initalData = [...this.state.initalData];
        initalData.map((item, index)=>{
            if(item.name.toString().indexOf(value) !== -1 || item.code.toString().indexOf(value) !== -1){
                data.push(item)
            }
        })
        return data;
    }

    onSearch = (value)=>{
        let searchValue = value.target? value.target.value : value;
        this.setState({
            searchValue
        }, ()=>{
            let data = this.filterTableData(searchValue);
            this.setState({
                tableData : [...data]
            })
        })
       
    }
    //通过子组件控制高阶组件的状态state
    setCurStateByWrapCom = (params)=>{
        let {
            pkMap,
            tableData,
        } = this.state;
        this.setState(params, ()=>{
            this.state.hasSelectedValue.map((item)=>{
                let index = -1;
                if(item.pkMeasureindex){
                    index = pkMap.indexOf(item.pkMeasureindex);
                }else  if(item.pkMeasureIndex){
                    index = pkMap.indexOf(item.pkMeasureIndex);
                }
                if(index !== -1){
                    tableData[index]["_checked"] = true;
                    tableData[index]["pkPlanIndex"] = item.pkPlanIndex;
                    tableData[index]["changeFlag"] = item.changeFlag;

                }
            })

            this.setState({
                tableData : [...tableData],
                selectedValue : [...this.state.hasSelectedValue]
            })
        })
    }
    mapTableData = (tableData)=>{
        let data = [];
        tableData.map((item, index)=>{
            data.push(item.pkMeasureindex)
        })

        tableData = this.handleDataStructor(tableData);
        
        this.setState({
            pkMap : [...data],
            tableData : [...tableData],
            initalData :[...tableData],
            searchValue:'',
            selectedValue :[],
            hasSelectedValue :[],
        })
    }

    handleDataStructor = (data) =>{
        data.map((item, index)=>{
            item["index"] = index ;
            item["key"] = index ;
            item["pkMeasureIndex"] = item.pkMeasureIndex;
        })
        return data;
    }

    setShowChooseTargetModal = ()=>{
        this.setState({
            showChooseModal : true
        }, ()=>{
            this.init();
        })
    }
    close = (operateButton) =>{
        this.setState({
            showChooseModal : false
        }, ()=>{
            if(operateButton === "confirm"){
                this.refs["[object Object]"].setCurStateByWrapCom({
                    showModal: true,
                    tableData: JSON.parse(JSON.stringify(this.state.hasSelectedValue)),
                    initalData : [...this.state.hasSelectedValue],
                });
                this.setState({
                    from :'' ,
                    selectedValue :[...this.state.hasSelectedValue],
                })
            }else if( this.state.from === "chooseTarget"&&operateButton === "close"  || this.state.from === "chooseTarget"&&operateButton === "cancel"){
                this.refs["[object Object]"].setCurStateByWrapCom({
                    showModal: true,
                    tableData: JSON.parse(JSON.stringify(this.state.selectedValue)),
                    initalData : [...this.state.selectedValue],
                });
                this.setState({
                    from :'' ,
                })
            }else if(operateButton === "close" ){
                this.setState({
                    from :'' ,
                    tableData:[],
                    initalData :[],
                    selectedValue :[],
                    hasSelectedValue:[]
                })
            }
        })
    }
    
    getSelectedDataFunc=(selectedList,record,index)=>{
      
        this.findHasSelectedNode(selectedList, index)
    }
    
    findHasSelectedNode=(selectedList, index)=>{
        
        selectedList.map((item, index)=>{
            this.state.selectedValue.map((innerItem, innerIndex)=>{
                if( item.pkMeasureindex === innerItem.pkMeasureindex || item.pkMeasureindex  === innerItem.pkMeasureIndex){
                    selectedList[index] = innerItem;
                    selectedList[index].key = item.key;
                    selectedList[index].index = item.index;
                }
            })
        })
        if(selectedList.length < this.state.hasSelectedValue.length){
            this.state.hasSelectedValue.splice(index, 1)
        }
        this.setState({
            hasSelectedValue : [...selectedList],
        })
    }

    render() {
        let {
            showChooseModal,
            columns,
            tableData,
            searchValue,
            hasSelectedValue
        } = this.state;
        return (
            <div>
               <WrappedComponent {...this} ref = {this}/>
                <Modal
                    backdrop = {false}
                    show = {showChooseModal}
                    onHide = {()=>this.close("close")}
                    size = {"xlg"}
                >
                    <Modal.Header closeButton className={"targetModalheader"}>
                        <Modal.Title>指标列表</Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                        <div  className={'search-header'}>
                            <div className={'search-header-search'}>
                                <FormControl
                                    value={searchValue}
                                    onChange = {this.onSearch}
                                    placeholder="请输入指标编码或名称"
                                    emptyText={() => '暂无数据'}
                                    className={'searchFormControl'}
                                    showClose = {true}
                                />
                                <Icon className="search-icon" type='uf uf-search-light' />
                            </div>
                        </div>

                        <MultiSelectTable 
                            columns={columns}
                            data = {tableData}
                            showRowNum = {true}
                            className = {"scroll-table-target"}
                            multiSelect={{
                                type: "checkbox"
                            }}
                            getSelectedDataFunc= {(selectedList,record,index)=>this.getSelectedDataFunc(selectedList,record,index)}
                        />
                    </Modal.Body>
                    <Modal.Footer className={"chooseTargetFooter"}>
                        <span>{`已选（${hasSelectedValue.length}）`}</span>
                        <div className={"footerButton"}>
                            <Button onClick={()=>this.close("cancel")} className = {"cancel"} >取消</Button>
                            <Button 
                                onClick={()=>this.close("confirm")} 
                                className = {"confirm"} 
                                disabled ={this.state.hasSelectedValue.length ? false: true}
                                bordered
                            >确认</Button>
                        </div>
                        <span></span>
                    </Modal.Footer>
                </Modal>
            </div>
        );
    }
}
